package com.jwx.controller;

import com.jwx.pojo.Result;
import com.jwx.pojo.User;
import com.jwx.service.UserService;
import com.jwx.utils.JwtUtil;
import com.jwx.utils.Md5Util;
import com.jwx.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.swing.plaf.TreeUI;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.util.StringUtils.hasLength;

@RestController//UserController类加上注解，这个类就是Controller，返回值是一个JSON对象
@RequestMapping("/user")//这个注解可以加到方法上，也可以加到类上
@Validated
public class Usercontroller {
@Resource
private UserService userService;
@PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,
                           @Pattern(regexp = "^\\S{5,16}$") String password) {
    User ReturnName = userService.findUserByName(username);

    if (ReturnName == null) {
        String md5String = Md5Util.getMD5String(password);
        userService.register(username, md5String);
        return Result.success();
    }else {
        return Result.error("执行错误");
    }
    }
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username,
                        @Pattern(regexp = "^\\S{5,16}$") String password){

        User userName = userService.findUserByName(username);
        if (username==null){
            return Result.error("登陆失败");
        }
        String md5String = Md5Util.getMD5String(password);

        if (md5String.equals(userName.getPassword())){
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id",userName.getId());
            claims.put("username",userName.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("登录失败");
    }
    @GetMapping ("/info")
    public Result userInfo(){
//        Map<String, Object> stringObjectMap = JwtUtil.parseToken(token);
        Map<String,Object> o = ThreadLocalUtil.get();
        String username =(String) o.get("username");
        User user = userService.findUserByName(username);
        return Result.success(user);
    }
/*
    问题：在拦截器中对token进行了判断，而在用户详细方法中又进行了解析，代码重复
    解决：我们可以使用ThreadLocal来解决
    ThreadLocal时是一个类，提供线程布局变量
    用法：用来存取数据：set()/get()
    线程安全
 */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){//requestbody注解表示前端请求的数据是JSON对象
        userService.update(user);
        return Result.success();
    }
   @PatchMapping("/updateAvatar")
    public Result updateAvater(@RequestParam  @URL String avatarUrl){//如果方法形参与请求参数不同可以使用Param注解
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params){
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        //判断是否合规
        if (!StringUtils.hasLength(oldPwd)||StringUtils.hasLength(newPwd)||StringUtils.hasLength(newPwd)){
            return Result.error("确实必要的参数");
        }
//        原密码是否正确？调用Userservice根据用户名拿到密码
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User userByName = userService.findUserByName(username);
        if (userByName.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码填写不正确");
        }
        if (!rePwd.equals(newPwd)){
            return Result.error("两次填写密码不一致");
        }
        //调用业务层更新密码
        userService.updatePwd(newPwd);
        return Result.success();
    }
}
